import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { fetchUserInfo, login as loginApi, logout as logoutApi } from '@/api/endpoints/auth';
import type { UserInfo } from '@/api/endpoints/auth';
import { showError, showSuccess } from '@/lib/toast';
import router from '@/router';

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(null);
  const refreshToken = ref<string | null>(null);
  const user = ref<UserInfo | null>(null);
  const isAuthenticated = ref<boolean>(false);
  const isLoading = ref<boolean>(false);

  // 计算属性
  const isLoggedIn = computed(() => isAuthenticated.value && !!token.value);

  // 方法
  const setToken = (newToken: string, newRefreshToken: string) => {
    token.value = newToken;
    refreshToken.value = newRefreshToken;
    isAuthenticated.value = true;
  };

  const setUser = (userData: UserInfo) => {
    user.value = userData;
  };

  const login = async (email: string, password: string) => {
    try {
      isLoading.value = true;
      const { data } = await loginApi({ email, password });
      const { accessToken, refreshToken } = data;

      // 设置token和用户信息
      setToken(accessToken, refreshToken);

      // 获取用户信息
      const { data: userInfo } = await fetchUserInfo();
      setUser(userInfo);

      showSuccess('登录成功');

      // 登录成功后跳转到原始目标路径或首页
      const redirect = router.currentRoute.value.query.redirect as string;
      router.push(redirect || '/');

      return { success: true };
    } catch (error: any) {
      showError(error.message || '登录失败，请检查网络连接');
      throw error;
    } finally {
      isLoading.value = false;
    }
  };

  const logout = async () => {
    try {
      // 调用登出接口
      await logoutApi();
    } catch (error) {
      console.error('登出接口调用失败:', error);
    } finally {
      // 无论接口是否成功，都清除本地状态
      clearAuth();
    }
  };

  const clearAuth = () => {
    token.value = null;
    refreshToken.value = null;
    user.value = null;
    isAuthenticated.value = false;

    // 跳转到登录页
    router.push('/login');
  };

  const checkAuth = () => {
    return isAuthenticated.value && !!token.value && !!user.value;
  };

  return {
    // 状态
    token,
    user,
    isAuthenticated,
    isLoading,

    // 计算属性
    isLoggedIn,

    // 方法
    setToken,
    setUser,
    login,
    logout,
    clearAuth,
    checkAuth,
  };
}, {
  // 持久化配置
  persist: {
    key: 'auth-store',
    storage: sessionStorage,
    paths: ['token', 'refreshToken', 'user', 'isAuthenticated'],
  } as any,
});
